#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time       : 2025/8/6 8:22
# @Author     : cfg
# @File       : main.py
# @Software   : PyCharm
# @Description: The description of this file.
import os.path

import pygame
from pygame.locals import KEYDOWN

from statics.color import Color
from statics.game_variable import GameVariable
from utils.page_renderer import home_page_render, game_page_render, pause_page_render, readme_page_render, \
    success_page_render, died_page_render
from utils.game_utils import show_message, key_listener, pause_page_key_listener

pygame.init()

# load saved datas
if os.path.exists("save_data.dat"):
    GameVariable.home_menu_num = 5
else:
    GameVariable.home_menu_num = 4

# create window
window_size = (800, 600)
screen = pygame.display.set_mode(window_size)
pygame.display.set_caption("gluttonous_snake")

# create background
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((0, 0, 0))

paused_surface = pygame.Surface(screen.get_size())
paused_surface.fill((59, 85, 86))
paused_surface.set_alpha(220)

died_surface = pygame.Surface(screen.get_size())
died_surface.fill(Color.failure)
died_surface.set_alpha(220)

# create clock
clock = pygame.time.Clock()

while not GameVariable.exited:

    # when paused
    if GameVariable.paused:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                GameVariable.exited = True
            elif event.type == KEYDOWN:
                if GameVariable.current_message:
                    GameVariable.current_message = ""
                else:
                    pause_page_key_listener(event.key)

    # when game running
    else:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                GameVariable.exited = True
            elif event.type == KEYDOWN:
                key_listener(event.key)

        screen.blit(background, (0, 0))
        # page render
        if GameVariable.current_page == GameVariable.home_page:
            home_page_render(background)
        if GameVariable.current_page == GameVariable.game_page:
            game_page_render(background)
        if GameVariable.current_page == GameVariable.readme_page:
            readme_page_render(background)
        if GameVariable.current_page == GameVariable.success_page:
            success_page_render(background)
        if GameVariable.current_page == GameVariable.died_page:
            died_page_render(screen, died_surface)

    # if game paused, render the pause page
    if GameVariable.paused:
        screen.blit(background, (0, 0))
        pause_page_render(screen, paused_surface)

    # if exist message, render the message
    if GameVariable.current_message:
        show_message(screen, GameVariable.current_message)

    pygame.display.flip()
    clock.tick(GameVariable.tick)

pygame.quit()
